﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using Model;
using Service;
using Resources;

public partial class sparepartView : System.Web.UI.Page
{
    public int TotalIn;
    public int TotalOut;
    public int Balance;
    IList<SparepartTempObject> SparepartList = new List<SparepartTempObject>();

    protected void Page_Load(object sender, EventArgs e)
    {

        txtHiddenEquipmentId.Text = Request.QueryString["informationId"];

        if (!new Utility().TestPermissions(Resource.PermissionViewSparepart))
        {
            lblMessageValidate.Text = Resource.Permission;
            lblTotalEquipment.Visible = false;
            grdEquipment.Visible = false;
            return;
        }
        else
        {
            txtHiddenEquipmentId.Text = Request.QueryString["informationId"];
            if (Session["whereClause"] == null)
                Session["whereClause"] = txtHiddenWhereClause.Text;
            if (Session["orderByClause"] == null)
                Session["orderByClause"] = txthiddenOrderbyClause.Text;

            new Utility().SetRowToDisplay(grdEquipment, Session["rowsToSDisplay"]);
            if (!IsPostBack)
            {
                // to avoid loading for the first time

                Session["informationId"] = Request.QueryString["informationId"];
                Session["defaultTabIndex"] = Request.QueryString["tabIndex"];
                grdGroupeSoftware1.Visible = true;
                if ((Request.QueryString["detail"] == null))
                {

                    if ((Request.QueryString["delete"] == null))
                    {
                        txtHiddenWhereClause.Text = "and SPAREPART.SPAREPARTID='0'";
                        lblTotalEquipment.Text = "Total Spareparts : 0";
                    }
                    else
                    {
                        int equipmentId = Request.QueryString["equipmentId"] != null
                                              ? Int32.Parse(Request.QueryString["equipmentId"])
                                              : 0;
                        new StockService().Delete(equipmentId);
                        txtHiddenWhereClause.Text = Session["whereClause"].ToString();
                        txthiddenOrderbyClause.Text = Session["orderByClause"].ToString();
                        SparepartList = new DirectService().DataTableToIListSpareparts(txtHiddenWhereClause.Text,
                                                                                      txthiddenOrderbyClause.Text);
                        
                        lblTotalEquipment.Text = "Total Spareparts : " + SparepartList.Count;
                    }
                }
                else
                {
                    txtHiddenWhereClause.Text = Session["whereClause"].ToString();
                    txthiddenOrderbyClause.Text = Session["orderByClause"].ToString();
                    SparepartList = new DirectService().DataTableToIListSpareparts(txtHiddenWhereClause.Text,
                                                                              txthiddenOrderbyClause.Text);
                   
                    lblTotalEquipment.Text = "Total Spareparts : " + SparepartList.Count;
                }


                if (Session["pageIndex"] != null)
                {
                    grdEquipment.PageIndex = Int32.Parse(Session["pageIndex"].ToString());

                }


                /* 
                 * 1. number of equipments
                 * 2. select the element 
                 * */
                txtHiddenPageIndex.Text = "0";
            }
            else
            {
                grdGroupeSoftware1.Visible = false;
                txtHiddenPageIndex.Text = "0";
                SparepartList = new DirectService().DataTableToIListSpareparts(GetWhereClause(), GetOrderClause());
                
                lblTotalEquipment.Text = "Total Spareparts : " + SparepartList.Count;

                if (SparepartList.Count == 0)
                {
                    grdGroupeSoftware1.Visible = true;
                    lblBalanceText.Visible = false;
                    lblTotalInText.Visible = false;
                    lblTotalOutText.Visible = false;
                   
                }
                else
                {
                    grdEquipment.Visible = true;
                    lblBalanceText.Visible = true;
                    lblTotalInText.Visible = true;
                    lblTotalOutText.Visible = true;
                    grdGroupeSoftware1.Visible = false;
                   
                }
            }
            DisplayTotalAmount();
            grdEquipment.PageIndex = !String.IsNullOrEmpty(txtHiddenPageIndex.Text)
                                         ? Int32.Parse(txtHiddenPageIndex.Text)
                                         : 0;
        }
    }
    

    private void DisplayTotalAmount()
    {
        lblTotalIn.Text = GetTotalIn().ToString();
        lblTotalOut.Text = GetTotalOut().ToString();
        lblTotalBalance.Text = GetTotalBalance().ToString();
    }
    public int GetTotalIn()
    {
        return SparepartList.Count != 0 ? SparepartList[SparepartList.Count-1].TotalIn : 0;
    }
    public int GetTotalOut()
    {
        return SparepartList.Count != 0 ? SparepartList[SparepartList.Count - 1].TotalOut : 0;
    }
    public int GetTotalBalance()
    {
        return SparepartList.Count != 0 ? SparepartList[SparepartList.Count - 1].Balance : 0;
    }
    protected void grdEquipment_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdEquipment.PageIndex = e.NewPageIndex;
        txtHiddenPageIndex.Text = grdEquipment.PageIndex.ToString();
        Session["pageIndex"] = grdEquipment.PageIndex;

    }
    protected void grdEquipment_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {

    }
    protected void grdEquipment_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
    protected void grdEquipment_RowDataBound1(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            if (Int32.Parse(DataBinder.Eval(e.Row.DataItem, "Balance").ToString()) <
                Int32.Parse(DataBinder.Eval(e.Row.DataItem, "Min").ToString()))
                e.Row.BackColor = Utility.GetRemarkableHightLightColor();

            if (Int32.Parse(DataBinder.Eval(e.Row.DataItem, "Balance").ToString()) <
                Int32.Parse(DataBinder.Eval(e.Row.DataItem, "Min").ToString()))
                e.Row.BackColor = Utility.GetRemarkableHightLightColor();


        }

    }
    public int GetPageIndex()
    {
        return Session["pageIndex"] != null
                   ?
                       Int32.Parse(Session["pageIndex"].ToString())
                   : 0;
    }
    public int GetTabIndex()
    {
        int tabIndex = Request.QueryString["tabIndex"] != null
                        ?
                            Int32.Parse(Request.QueryString["tabIndex"])
                        : 0;
        if (Session["defaultTabIndex"] != null)
        {
            tabIndex = Int32.Parse(Session["defaultTabIndex"].ToString());
            Session["defaultTabIndex"] = null;
        }

        return tabIndex;
    }
    public string GetDisplayMode()
    {
        return Request.QueryString["detail"];
    }
    protected void btnValidate_Click(object sender, EventArgs e)
    {

        if (!new Utility().TestPermissions(Resource.PermissionViewSparepart))
        {
            lblMessageValidate.Text = Resource.Permission;
            return;
        }
        lblMessageValidate.Visible = false;
        Session["whereClause"] = GetWhereClause();
        Session["orderByClause"] = GetOrderClause();
        txthiddenOrderbyClause.Text = GetOrderClause();
        txtHiddenWhereClause.Text = GetWhereClause();
        Session["defaultTabIndex"] = 0;

        // empty textboxes after searched clicked
        txtPurchaseDate.Text = string.Empty;
        txtPONumber.Text = string.Empty;
        txtEndWarrantyDate.Text = string.Empty;

    }
    protected string GetOrderClause()
    {
        return " Order by EQUIPMENTPURCHASEINFORMATION.PURCHASEDATE";
    }
    protected string GetWhereClause()
    {
        string whereClause = string.Empty;
        string and = "";
        string str = "";

        
        if (drlCompany.SelectedIndex >0)
        {
            str = "(companyConcerning.companyid = " + this.drlCompany.SelectedValue + ")";
            and = " and ";
        }

        if (drlSystem.SelectedIndex >0)
        {
            str += and + " (system.systemid=" + this.drlSystem.SelectedValue + ")";
            and = " and ";
        }

        if (drlEquipmentType.SelectedIndex >0)
        {
            str += and + " (TypeEquipment.typeEquipementID=" + drlEquipmentType.SelectedValue + ")";
            and = " and ";
        }

        if (drlModel.SelectedIndex >0)
        {
            str += and + " (model.modelID=" + this.drlModel.SelectedValue + ")";
            and = " and ";
        }
        if (txtPurchaseDate.Text != string.Empty)
        {

            DateTime.Parse(txtPurchaseDate.Text, new CultureInfo("en-US", true));
            str += and + "( purchaseDate=convert(datetime,'" + txtPurchaseDate.Text + "', 101) )";
            and = " and ";

        }
        if (txtEndWarrantyDate.Text != string.Empty)
        {


            str += and + "( SPAREPARTPURCHASEINFORMATION.DATEEND=convert(datetime,'" + txtEndWarrantyDate.Text + "', 101) )";
            and = " and ";

        }
        if (txtPONumber.Text != string.Empty)
        {


            str += and + "( SPAREPARTPURCHASEINFORMATION.POReferenceNumber= '"+txtPONumber.Text+ "') ";
            and = " and ";

        }

        if (!String.IsNullOrEmpty(str))
            whereClause = " and " + str + " ";
        return whereClause;
    }
    protected void grdEquipment_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        if (e.CommandName.Equals("Select"))
        {
            int informationId = Convert.ToInt32(grdEquipment.DataKeys[Convert.ToInt32(e.CommandArgument)].Value);
            Session["informationId"] = informationId;
            Session["defaultTabIndex"] = 1;
            Session["rowSelectedIndex"] = Convert.ToInt32(e.CommandArgument);
        }
        new Utility().SetSelectedColorToGridView(e, grdEquipment);
    }
}
